<template>
  <Dialog v-model="dialogVisible" title="巡班违纪记录汇总报告" width="1200px" :fullscreen="isFullscreen">
    <div v-loading="loading" id="summaryContent" class="summary-content">
      <!-- 顶部操作栏 -->
      <div class="action-bar">
        <div class="action-left">
          <span class="report-main-title">巡班违纪记录汇总报告</span>
        </div>
        <div class="action-right">
          <el-date-picker
            v-model="summaryDateRange"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            style="width: 320px; margin-right: 10px;"
            clearable
            @change="handleDateRangeChange"
          />
          <el-button size="default" @click="refreshData">
            <Icon icon="ep:refresh" class="mr-1" /> 
            刷新数据
          </el-button>
          <el-dropdown @command="handleExportCommand" trigger="click" style="margin-left: 10px;">
            <el-button type="primary" size="default">
              <Icon icon="ep:download" class="mr-1" /> 
              导出
              <Icon icon="ep:arrow-down" class="ml-1" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="chart">
                  <Icon icon="ep:picture" class="mr-2" /> 导出图表图片
                </el-dropdown-item>
                <el-dropdown-item command="excel">
                  <Icon icon="ep:document" class="mr-2" /> 导出详细数据Excel
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <!-- 报告标题 -->
      <div class="report-header">
        <h2 class="report-title">巡班违纪记录汇总报告</h2>
        <p class="report-date">生成时间: {{ currentDateTime }}</p>
        <div v-if="hasFilters" class="filter-tags">
          <el-tag v-if="filterInfo.classDate" type="info" size="small">
         日期: {{ filterInfo.classDate }}
          </el-tag>
          <el-tag v-if="filterInfo.teacherName" type="success" size="small">
            授课老师: {{ filterInfo.teacherName }}
          </el-tag>
          <el-tag v-if="filterInfo.patrolTeacherName" type="warning" size="small">
             巡班老师: {{ filterInfo.patrolTeacherName }}
          </el-tag>
          <el-tag v-if="filterInfo.classroom" type="primary" size="small">
             教室: {{ filterInfo.classroom }}
          </el-tag>
        </div>
      </div>

      <!-- 核心数据统计卡片 -->
      <el-row :gutter="20" class="stats-cards">
        <el-col :span="6">
          <div class="stat-card success">
            <div class="stat-value">{{ summaryData.totalCount }}</div>
            <div class="stat-label">总违纪次数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card success">
            <div class="stat-value">{{ summaryData.totalPersonCount }}</div>
            <div class="stat-label">总违纪人数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card success">
            <div class="stat-value">{{ summaryData.classCount }}</div>
            <div class="stat-label">涉及班级数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card success">
            <div class="stat-value">{{ summaryData.teacherCount }}</div>
            <div class="stat-label">涉及教师数</div>
          </div>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-section">
        <!-- 违纪类型分布 -->
        <el-col :span="12">
          <div class="chart-card">
            <h3 class="chart-title">
              <Icon icon="ep:pie-chart" class="mr-2" />
              违纪类型分布
            </h3>
            <div ref="pieChartRef" style="height: 350px;"></div>
          </div>
        </el-col>

        <!-- 每周违纪趋势 -->
        <el-col :span="12">
          <div class="chart-card">
            <h3 class="chart-title">
              <Icon icon="ep:histogram" class="mr-2" />
              每周违纪趋势
            </h3>
            <div ref="lineChartRef" style="height: 350px;"></div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="chart-section">
        <!-- 班级违纪排名 -->
        <el-col :span="12">
          <div class="chart-card">
            <h3 class="chart-title">
              <Icon icon="ep:trophy" class="mr-2" />
              班级违纪排名 TOP10
            </h3>
            <div ref="classBarChartRef" style="height: 400px;"></div>
          </div>
        </el-col>

        <!-- 教师课堂违纪统计 -->
        <el-col :span="12">
          <div class="chart-card">
            <h3 class="chart-title">
              <Icon icon="ep:user" class="mr-2" />
              教师课堂违纪统计 TOP10
            </h3>
            <div ref="teacherBarChartRef" style="height: 400px;"></div>
          </div>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <div class="data-table-card">
        <h3 class="chart-title">
          <Icon icon="ep:document" class="mr-2" />
          详细数据列表
        </h3>
        <el-table :data="summaryData.detailList" stripe border max-height="400">
          <el-table-column type="index" label="排名" width="60" align="center" />
          <el-table-column prop="className" label="班级" width="150" />
          <el-table-column prop="totalCount" label="违纪次数" width="100" align="center" sortable />
          <el-table-column prop="totalPersons" label="违纪人数" width="100" align="center" sortable />
          <el-table-column prop="mainViolationType" label="主要违纪类型" width="150" />
          <el-table-column prop="mainTeacher" label="主要授课教师" width="120" />
          <el-table-column prop="latestDate" label="最近违纪日期" width="120" />
          <el-table-column prop="latestCourse" label="最近违纪课程" min-width="150" />
        </el-table>
      </div>

      <!-- 报告页脚 -->
      <div class="report-footer">
        <p>本报告由巡班管理系统自动生成</p>
        <p>数据来源: 巡班违纪记录数据库</p>
      </div>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { PatrolApi } from '@/api/ao/patrol'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

defineOptions({ name: 'PatrolSummary' })

const message = useMessage()
const dialogVisible = ref(false)
const loading = ref(false)
const isFullscreen = ref(false)
const currentDateTime = ref('')
const hasFilters = ref(false)
const filterInfo = ref<any>({})

// 图表引用
const pieChartRef = ref()
const lineChartRef = ref()
const classBarChartRef = ref()
const teacherBarChartRef = ref()

// 汇总数据
const summaryData = ref({
  totalCount: 0,
  totalPersonCount: 0,
  classCount: 0,
  teacherCount: 0,
  violationTypes: [] as any[],
  weeklyTrend: [] as any[],
  classRanking: [] as any[],
  teacherRanking: [] as any[],
  detailList: [] as any[]
})

// 时间范围选择器
const summaryDateRange = ref([])
// 保存原始查询参数
const originalQueryParams = ref<any>({})

/** 打开对话框 */
const open = async (queryParams: any) => {
  dialogVisible.value = true
  loading.value = true
  
  // 保存原始查询参数
  originalQueryParams.value = { ...queryParams }
  
  // 如果传入的queryParams有classDate，设置到时间选择器
  if (queryParams.classDate && queryParams.classDate.length > 0) {
    summaryDateRange.value = queryParams.classDate
  } else {
    summaryDateRange.value = []
  }
  
  // 生成当前时间
  const now = new Date()
  currentDateTime.value = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
  
  // 加载数据
  await loadData()
}

/** 加载数据的通用方法 */
const loadData = async () => {
  loading.value = true
  
  // 构建查询参数，使用当前的时间范围
  const queryParams = {
    ...originalQueryParams.value,
    classDate: summaryDateRange.value && summaryDateRange.value.length > 0 
      ? summaryDateRange.value 
      : undefined
  }
  
  // 生成当前时间
  const now = new Date()
  currentDateTime.value = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`
  
  // 更新筛选条件信息
  filterInfo.value = {
    classDate: queryParams.classDate?.[0] ? `${queryParams.classDate[0]} ~ ${queryParams.classDate[1]}` : '',
    teacherName: queryParams.teacherName || '',
    patrolTeacherName: queryParams.patrolTeacherName || '',
    classroom: queryParams.classroom || ''
  }
  hasFilters.value = !!(filterInfo.value.classDate || filterInfo.value.teacherName || filterInfo.value.patrolTeacherName || filterInfo.value.classroom)
  
  try {
    // 分页获取所有数据（每次最多100条）
    let allData: any[] = []
    let pageNo = 1
    const pageSize = 100
    let hasMore = true
    
    while (hasMore) {
      const data = await PatrolApi.getPatrolPage({
        ...queryParams,
        pageNo: pageNo,
        pageSize: pageSize
      })
      
      if (data.list && data.list.length > 0) {
        allData = allData.concat(data.list)
        
        // 检查是否还有更多数据
        if (data.list.length < pageSize || allData.length >= data.total) {
          hasMore = false
        } else {
          pageNo++
        }
      } else {
        hasMore = false
      }
    }
    
    // 处理汇总数据
    processSummaryData(allData)
    
    // 等待DOM更新后渲染图表
    await nextTick()
    renderCharts()
  } catch (error) {
    console.error('加载汇总数据失败:', error)
    message.error('加载汇总数据失败')
  } finally {
    loading.value = false
  }
}

/** 刷新数据 */
const refreshData = async () => {
  await loadData()
  message.success('数据已刷新')
}

/** 时间范围变化处理 */
const handleDateRangeChange = () => {
  // 时间范围变化时自动刷新数据
  loadData()
}

/** 归类和清洗违纪类型 */
const normalizeViolationType = (type: string): string => {
  if (!type || type === '未分类') return '未分类'
  
  // 转换为小写便于匹配
  const lowerType = type.toLowerCase().trim()
  
  // 睡觉相关
  if (lowerType.includes('睡觉') || lowerType.includes('睡眠') || lowerType.includes('趴桌')) {
    return '睡觉'
  }
  
  // 玩手机相关
  if (lowerType.includes('玩手机') || lowerType.includes('手机') || lowerType.includes('看手机')) {
    return '玩手机'
  }
  
  // 打瞌睡相关
  if (lowerType.includes('打瞌睡') || lowerType.includes('瞌睡') || lowerType.includes('犯困')) {
    return '打瞌睡'
  }
  
  // 玩游戏相关
  if (lowerType.includes('玩游戏') || lowerType.includes('游戏') || lowerType.includes('打游戏')) {
    return '玩游戏'
  }
  
  // 说话/聊天相关
  if (lowerType.includes('说话') || lowerType.includes('聊天') || lowerType.includes('讲话') || lowerType.includes('交谈')) {
    return '说话聊天'
  }
  
  // 吃东西相关
  if (lowerType.includes('吃东西') || lowerType.includes('吃零食') || lowerType.includes('进食')) {
    return '吃东西'
  }
  
  // 迟到相关
  if (lowerType.includes('迟到') || lowerType.includes('晚到')) {
    return '迟到'
  }
  
  // 早退相关
  if (lowerType.includes('早退') || lowerType.includes('提前离开')) {
    return '早退'
  }
  
  // 旷课相关
  if (lowerType.includes('旷课') || lowerType.includes('缺课') || lowerType.includes('逃课')) {
    return '旷课'
  }
  
  // 不专心/走神相关
  if (lowerType.includes('不专心') || lowerType.includes('走神') || lowerType.includes('注意力') || lowerType.includes('分心')) {
    return '不专心'
  }
  
  // 吵闹相关
  if (lowerType.includes('吵闹') || lowerType.includes('喧哗') || lowerType.includes('大声')) {
    return '吵闹'
  }
  
  // 其他行为违纪
  if (lowerType.includes('打架') || lowerType.includes('打闹')) {
    return '打架打闹'
  }
  
  // 仪容仪表
  if (lowerType.includes('仪容') || lowerType.includes('仪表') || lowerType.includes('着装')) {
    return '仪容仪表'
  }
  
  // 如果不匹配任何规则，返回原始类型（但要清理格式）
  return type.trim()
}

/** 处理汇总数据 */
const processSummaryData = (list: any[]) => {
  // 1. 基础统计
  summaryData.value.totalCount = list.length
  summaryData.value.totalPersonCount = list.reduce((sum, item) => sum + (item.violationCount || 0), 0)
  
  const classSet = new Set(list.map(item => item.className).filter(Boolean))
  const teacherSet = new Set(list.map(item => item.teacherName).filter(Boolean))
  summaryData.value.classCount = classSet.size
  summaryData.value.teacherCount = teacherSet.size
  
  // 2. 违纪类型统计 - 先清洗和归类
  const typeMap = new Map()
  list.forEach(item => {
    let type = item.violationType || '未分类'
    
    // 清洗和归类违纪类型
    type = normalizeViolationType(type)
    
    typeMap.set(type, (typeMap.get(type) || 0) + 1)
  })
  summaryData.value.violationTypes = Array.from(typeMap.entries())
    .map(([name, value]) => ({ name, value }))
    .sort((a, b) => b.value - a.value)
  
  // 3. 每周违纪趋势（按日期分组）
  const dateMap = new Map()
  list.forEach(item => {
    if (item.classDate) {
      const date = item.classDate.split(' ')[0] // 只取日期部分
      dateMap.set(date, (dateMap.get(date) || 0) + 1)
    }
  })
  summaryData.value.weeklyTrend = Array.from(dateMap.entries())
    .map(([date, count]) => ({ date, count }))
    .sort((a, b) => a.date.localeCompare(b.date))
  
  // 4. 班级违纪排名
  const classMap = new Map()
  list.forEach(item => {
    const className = item.className || '未知班级'
    if (!classMap.has(className)) {
      classMap.set(className, {
        className,
        count: 0,
        persons: 0,
        records: []
      })
    }
    const classData = classMap.get(className)
    classData.count++
    classData.persons += item.violationCount || 0
    classData.records.push(item)
  })
  summaryData.value.classRanking = Array.from(classMap.values())
    .sort((a, b) => b.count - a.count)
    .slice(0, 10)
  
  // 5. 教师违纪统计
  const teacherMap = new Map()
  list.forEach(item => {
    const teacherName = item.teacherName || '未知教师'
    teacherMap.set(teacherName, (teacherMap.get(teacherName) || 0) + 1)
  })
  summaryData.value.teacherRanking = Array.from(teacherMap.entries())
    .map(([name, count]) => ({ name, count }))
    .sort((a, b) => b.count - a.count)
    .slice(0, 10)
  
  // 6. 详细列表数据
  summaryData.value.detailList = Array.from(classMap.values())
    .sort((a, b) => b.count - a.count)
    .map(classData => {
      // 统计该班级的主要违纪类型
      const typeCount = new Map()
      classData.records.forEach((record: any) => {
        const type = record.violationType || '未分类'
        typeCount.set(type, (typeCount.get(type) || 0) + 1)
      })
      const mainType = Array.from(typeCount.entries())
        .sort((a, b) => b[1] - a[1])[0]?.[0] || '无'
      
      // 统计主要授课教师
      const teacherCount = new Map()
      classData.records.forEach((record: any) => {
        const teacher = record.teacherName || '未知'
        teacherCount.set(teacher, (teacherCount.get(teacher) || 0) + 1)
      })
      const mainTeacher = Array.from(teacherCount.entries())
        .sort((a, b) => b[1] - a[1])[0]?.[0] || '无'
      
      // 最近一次违纪
      const latest = classData.records.sort((a: any, b: any) => 
        (b.classDate || '').localeCompare(a.classDate || '')
      )[0]
      
      return {
        className: classData.className,
        totalCount: classData.count,
        totalPersons: classData.persons,
        mainViolationType: mainType,
        mainTeacher: mainTeacher,
        latestDate: latest?.classDate?.split(' ')[0] || '',
        latestCourse: latest?.courseName || ''
      }
    })
}

/** 渲染图表 */
const renderCharts = () => {
  renderPieChart()
  renderLineChart()
  renderClassBarChart()
  renderTeacherBarChart()
}

/** 渲染饼图 - 违纪类型分布 */
const renderPieChart = () => {
  if (!pieChartRef.value) return
  
  const chart = echarts.init(pieChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: summaryData.value.violationTypes.map(item => item.name)
    },
    series: [
      {
        name: '违纪类型',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: summaryData.value.violationTypes
      }
    ],
    color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4']
  }
  chart.setOption(option)
}

/** 渲染折线图 - 每周违纪趋势 */
const renderLineChart = () => {
  if (!lineChartRef.value) return
  
  const chart = echarts.init(lineChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: summaryData.value.weeklyTrend.map(item => item.date)
    },
    yAxis: {
      type: 'value',
      name: '违纪次数'
    },
    series: [
      {
        name: '违纪次数',
        type: 'line',
        smooth: true,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(84, 112, 198, 0.4)' },
              { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
            ]
          }
        },
        data: summaryData.value.weeklyTrend.map(item => item.count)
      }
    ],
    color: ['#5470c6']
  }
  chart.setOption(option)
}

/** 渲染柱状图 - 班级排名 */
const renderClassBarChart = () => {
  if (!classBarChartRef.value) return
  
  const chart = echarts.init(classBarChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '违纪次数'
    },
    yAxis: {
      type: 'category',
      data: summaryData.value.classRanking.map(item => item.className).reverse()
    },
    series: [
      {
        name: '违纪次数',
        type: 'bar',
        data: summaryData.value.classRanking.map(item => item.count).reverse(),
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#ee6666' },
              { offset: 1, color: '#fac858' }
            ]
          },
          borderRadius: [0, 5, 5, 0]
        }
      }
    ]
  }
  chart.setOption(option)
}

/** 渲染柱状图 - 教师统计 */
const renderTeacherBarChart = () => {
  if (!teacherBarChartRef.value) return
  
  const chart = echarts.init(teacherBarChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '违纪次数'
    },
    yAxis: {
      type: 'category',
      data: summaryData.value.teacherRanking.map(item => item.name).reverse()
    },
    series: [
      {
        name: '违纪次数',
        type: 'bar',
        data: summaryData.value.teacherRanking.map(item => item.count).reverse(),
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#91cc75' },
              { offset: 1, color: '#3ba272' }
            ]
          },
          borderRadius: [0, 5, 5, 0]
        }
      }
    ]
  }
  chart.setOption(option)
}

/** 处理导出命令 */
const handleExportCommand = (command: string) => {
  if (command === 'chart') {
    exportChartAsImage()
  } else if (command === 'excel') {
    exportToExcel()
  }
}

/** 导出图表为图片 */
const exportChartAsImage = async () => {
  try {
    ElMessage.info('正在生成图表图片...')
    
    // 获取所有ECharts实例的图片
    let pieChartImage: HTMLImageElement | null = null
    let lineChartImage: HTMLImageElement | null = null
    let classBarChartImage: HTMLImageElement | null = null
    let teacherBarChartImage: HTMLImageElement | null = null
    
    // 获取饼图
    if (pieChartRef.value) {
      const pieChart = echarts.getInstanceByDom(pieChartRef.value)
      if (pieChart) {
        const pieDataUrl = pieChart.getDataURL({ type: 'png', pixelRatio: 2, backgroundColor: '#fff' })
        pieChartImage = await loadImage(pieDataUrl)
      }
    }
    
    // 获取折线图
    if (lineChartRef.value) {
      const lineChart = echarts.getInstanceByDom(lineChartRef.value)
      if (lineChart) {
        const lineDataUrl = lineChart.getDataURL({ type: 'png', pixelRatio: 2, backgroundColor: '#fff' })
        lineChartImage = await loadImage(lineDataUrl)
      }
    }
    
    // 获取班级排名条形图
    if (classBarChartRef.value) {
      const classBarChart = echarts.getInstanceByDom(classBarChartRef.value)
      if (classBarChart) {
        const classBarDataUrl = classBarChart.getDataURL({ type: 'png', pixelRatio: 2, backgroundColor: '#fff' })
        classBarChartImage = await loadImage(classBarDataUrl)
      }
    }
    
    // 获取教师违纪条形图
    if (teacherBarChartRef.value) {
      const teacherBarChart = echarts.getInstanceByDom(teacherBarChartRef.value)
      if (teacherBarChart) {
        const teacherBarDataUrl = teacherBarChart.getDataURL({ type: 'png', pixelRatio: 2, backgroundColor: '#fff' })
        teacherBarChartImage = await loadImage(teacherBarDataUrl)
      }
    }
    
    // 创建Canvas
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    if (!ctx) {
      message.error('浏览器不支持Canvas')
      return
    }
    
    // 设置Canvas尺寸（增加高度以容纳更多图表）
    canvas.width = 1200
    canvas.height = 1800
    
    // 背景色
    ctx.fillStyle = '#ffffff'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    
    // 绘制标题
    ctx.fillStyle = '#3c96f3'
    ctx.fillRect(50, 30, 1100, 100)
    
    // 绘制标题文字
    ctx.fillStyle = '#ffffff'
    ctx.font = 'bold 32px Arial'
    ctx.textAlign = 'center'
    ctx.fillText('巡班违纪记录汇总报告', 600, 75)
    
    ctx.font = '16px Arial'
    ctx.fillText(`生成时间: ${currentDateTime.value}`, 600, 105)
    
    // 绘制4个统计卡片
    const cardY = 160
    const cardWidth = 250
    const cardHeight = 120
    const cardGap = 30
    const startX = 50
    
    const cards = [
      { title: '总违纪次数', value: summaryData.value.totalCount, color: '#3c96f3' },
      { title: '总违纪人数', value: summaryData.value.totalPersonCount, color: '#3c96f3' },
      { title: '涉及班级数', value: summaryData.value.classCount, color: '#3c96f3' },
      { title: '涉及教师数', value: summaryData.value.teacherCount, color: '#3c96f3' }
    ]
    
    cards.forEach((card, index) => {
      const x = startX + (cardWidth + cardGap) * index
      
      // 绘制卡片背景
      ctx.fillStyle = card.color
      roundRect(ctx, x, cardY, cardWidth, cardHeight, 12)
      ctx.fill()
      
      // 绘制数值
      ctx.fillStyle = '#ffffff'
      ctx.font = 'bold 48px Arial'
      ctx.textAlign = 'center'
      ctx.fillText(String(card.value), x + cardWidth / 2, cardY + 60)
      
      // 绘制标签
      ctx.font = '16px Arial'
      ctx.fillText(card.title, x + cardWidth / 2, cardY + 95)
    })
    
    // 绘制ECharts图表
    let currentY = 320
    const chartWidth = 550
    const chartHeight = 300
    
    // 第一行：饼图和折线图
    if (pieChartImage || lineChartImage) {
      ctx.fillStyle = '#333333'
      ctx.font = 'bold 20px Arial, sans-serif'
      ctx.textAlign = 'left'
      
      if (pieChartImage) {
        ctx.fillText('违纪类型分布', 50, currentY)
        ctx.drawImage(pieChartImage, 50, currentY + 25, chartWidth, chartHeight)
      }
      
      if (lineChartImage) {
        ctx.fillText('每周违纪趋势', 620, currentY)
        ctx.drawImage(lineChartImage, 620, currentY + 25, chartWidth, chartHeight)
      }
      
      currentY += chartHeight + 70
    }
    
    // 第二行：班级排名和教师违纪统计
    const barChartHeight = 350
    if (classBarChartImage || teacherBarChartImage) {
      ctx.fillStyle = '#333333'
      ctx.font = 'bold 20px Arial, sans-serif'
      ctx.textAlign = 'left'
      
      if (classBarChartImage) {
        ctx.fillText('班级违纪排名 TOP10', 50, currentY)
        ctx.drawImage(classBarChartImage, 50, currentY + 25, chartWidth, barChartHeight)
      }
      
      if (teacherBarChartImage) {
        ctx.fillText('教师课堂违纪统计 TOP10', 620, currentY)
        ctx.drawImage(teacherBarChartImage, 620, currentY + 25, chartWidth, barChartHeight)
      }
      
      currentY += barChartHeight + 70
    }
    
    // 绘制违纪类型分布表格
    const tableY = currentY
    ctx.fillStyle = '#333333'
    ctx.font = 'bold 20px Arial'
    ctx.textAlign = 'left'
    ctx.fillText('违纪类型分布 TOP10', 50, tableY)
    
    // 表格头部
    const headerY = tableY + 40
    ctx.fillStyle = '#f5f5f5'
    ctx.fillRect(50, headerY, 500, 40)
    
    ctx.fillStyle = '#333333'
    ctx.font = 'bold 14px Arial'
    ctx.fillText('违纪类型', 70, headerY + 25)
    ctx.fillText('次数', 320, headerY + 25)
    ctx.fillText('占比', 420, headerY + 25)
    
    // 表格内容
    const top10Types = summaryData.value.violationTypes.slice(0, 10)
    top10Types.forEach((item, index) => {
      const rowY = headerY + 40 + index * 35
      
      // 背景
      if (index % 2 === 0) {
        ctx.fillStyle = '#fafafa'
        ctx.fillRect(50, rowY, 500, 35)
      }
      
      // 文字
      ctx.fillStyle = '#666666'
      ctx.font = '14px Arial'
      ctx.fillText(item.name, 70, rowY + 22)
      ctx.fillText(String(item.value), 320, rowY + 22)
      
      const percentage = ((item.value / summaryData.value.totalCount) * 100).toFixed(1) + '%'
      ctx.fillText(percentage, 420, rowY + 22)
    })
    
    // 绘制班级排名表格
    const rankTableY = tableY
    const rankTableX = 600
    ctx.fillStyle = '#333333'
    ctx.font = 'bold 20px Arial'
    ctx.textAlign = 'left'
    ctx.fillText('班级违纪排名 TOP10', rankTableX, rankTableY)
    
    // 表格头部
    const rankHeaderY = rankTableY + 40
    ctx.fillStyle = '#f5f5f5'
    ctx.fillRect(rankTableX, rankHeaderY, 550, 40)
    
    ctx.fillStyle = '#333333'
    ctx.font = 'bold 14px Arial'
    ctx.fillText('排名', rankTableX + 20, rankHeaderY + 25)
    ctx.fillText('班级', rankTableX + 70, rankHeaderY + 25)
    ctx.fillText('违纪次数', rankTableX + 320, rankHeaderY + 25)
    ctx.fillText('违纪人数', rankTableX + 440, rankHeaderY + 25)
    
    // 表格内容
    const top10Classes = summaryData.value.classRanking.slice(0, 10)
    top10Classes.forEach((item, index) => {
      const rowY = rankHeaderY + 40 + index * 35
      
      // 背景
      if (index % 2 === 0) {
        ctx.fillStyle = '#fafafa'
        ctx.fillRect(rankTableX, rowY, 550, 35)
      }
      
      // 文字
      ctx.fillStyle = '#666666'
      ctx.font = '14px Arial'
      ctx.fillText(String(index + 1), rankTableX + 30, rowY + 22)
      ctx.fillText(item.className, rankTableX + 70, rowY + 22)
      ctx.fillText(String(item.count), rankTableX + 340, rowY + 22)
      ctx.fillText(String(item.persons), rankTableX + 460, rowY + 22)
    })
    
    // 计算页脚位置（基于班级排名表格的底部）
    const footerY = Math.max(rankHeaderY + 40 + top10Classes.length * 35 + 40, 770)
    
    // 页脚
    ctx.fillStyle = '#999999'
    ctx.font = '12px Arial'
    ctx.textAlign = 'center'
    ctx.fillText('本报告由巡班管理系统自动生成', 600, footerY)
    ctx.fillText('数据来源: 巡班违纪记录数据库', 600, footerY + 20)
    
    // 转换为图片并下载
    canvas.toBlob((blob) => {
      if (blob) {
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `巡班违纪汇总报告_${currentDateTime.value.replace(/[: ]/g, '')}.png`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        message.success('图表图片导出成功')
      } else {
        message.error('图片生成失败')
      }
    }, 'image/png')
    
  } catch (error) {
    console.error('导出图表失败:', error)
    message.error('导出图表失败')
  }
}

// 辅助函数：绘制圆角矩形
const roundRect = (ctx: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, radius: number) => {
  ctx.beginPath()
  ctx.moveTo(x + radius, y)
  ctx.lineTo(x + width - radius, y)
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius)
  ctx.lineTo(x + width, y + height - radius)
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height)
  ctx.lineTo(x + radius, y + height)
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius)
  ctx.lineTo(x, y + radius)
  ctx.quadraticCurveTo(x, y, x + radius, y)
  ctx.closePath()
}

// 辅助函数：加载图片
const loadImage = (src: string): Promise<HTMLImageElement> => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => resolve(img)
    img.onerror = reject
    img.src = src
  })
}

/** 导出为Excel */
const exportToExcel = async () => {
  try {
    ElMessage.info('正在生成Excel文件...')
    
    // 准备Excel数据
    const excelData: any[] = []
    
    // 添加标题行
    excelData.push(['巡班违纪记录汇总报告'])
    excelData.push(['生成时间', currentDateTime.value])
    excelData.push([]) // 空行
    
    // 添加汇总统计
    excelData.push(['汇总统计'])
    excelData.push(['总违纪次数', summaryData.value.totalCount])
    excelData.push(['总违纪人数', summaryData.value.totalPersonCount])
    excelData.push(['涉及班级数', summaryData.value.classCount])
    excelData.push(['涉及教师数', summaryData.value.teacherCount])
    excelData.push([]) // 空行
    
    // 添加违纪类型分布
    excelData.push(['违纪类型分布'])
    excelData.push(['类型', '次数', '占比'])
    summaryData.value.violationTypes.forEach(item => {
      const percentage = ((item.value / summaryData.value.totalCount) * 100).toFixed(1)
      excelData.push([item.name, item.value, percentage + '%'])
    })
    excelData.push([]) // 空行
    
    // 添加班级违纪排名
    excelData.push(['班级违纪排名 TOP10'])
    excelData.push(['排名', '班级', '违纪次数', '违纪人数'])
    summaryData.value.classRanking.forEach((item, index) => {
      excelData.push([
        index + 1,
        item.className,
        item.count,
        item.persons
      ])
    })
    excelData.push([]) // 空行
    
    // 添加教师课堂违纪统计
    excelData.push(['教师课堂违纪统计 TOP10'])
    excelData.push(['排名', '教师', '违纪次数'])
    summaryData.value.teacherRanking.forEach((item, index) => {
      excelData.push([
        index + 1,
        item.name,
        item.count
      ])
    })
    excelData.push([]) // 空行
    
    // 添加详细数据列表
    excelData.push(['详细数据列表'])
    excelData.push(['排名', '班级', '违纪次数', '违纪人数', '主要违纪类型', '主要授课教师', '最近违纪日期', '最近违纪课程'])
    summaryData.value.detailList.forEach((item, index) => {
      excelData.push([
        index + 1,
        item.className,
        item.totalCount,
        item.totalPersons,
        item.mainViolationType,
        item.mainTeacher,
        item.latestDate,
        item.latestCourse
      ])
    })
    
    // 转换为CSV格式
    const csvContent = excelData.map(row => 
      row.map(cell => {
        // 处理包含逗号或换行的单元格
        const cellStr = String(cell || '')
        if (cellStr.includes(',') || cellStr.includes('\n') || cellStr.includes('"')) {
          return '"' + cellStr.replace(/"/g, '""') + '"'
        }
        return cellStr
      }).join(',')
    ).join('\n')
    
    // 添加BOM以支持中文
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    
    // 下载文件
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `巡班违纪汇总报告_${currentDateTime.value.replace(/[: ]/g, '')}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    message.success('Excel文件导出成功')
  } catch (error) {
    console.error('导出Excel失败:', error)
    message.error('导出Excel失败')
  }
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.summary-content {
  padding: 20px;
  background: #f5f7fa;
  min-height: 600px;
}

/* 顶部操作栏 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.action-left {
  display: flex;
  align-items: center;
}

.report-main-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.action-right {
  display: flex;
  gap: 10px;
}

/* 报告标题 */
.report-header {
  text-align: center;
  padding: 30px 20px;
//   background: linear-gradient(135deg, #fefeff 0%, #283f75 100%);
    background: #3c96f3;
  border-radius: 12px;
  margin-bottom: 20px;
  color: white;
}

.report-title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 10px;
}

.report-date {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 15px;
}

.filter-tags {
  display: flex;
  justify-content: center;
  gap: 10px;
  flex-wrap: wrap;
}

/* 统计卡片 */
.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  padding: 25px;
  border-radius: 12px;
  text-align: center;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  
  &:hover {
    transform: translateY(-5px);
  }
  
  &.primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
  
  &.warning {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  }
  
  &.success {
        background: #3c96f3;
  }
  
  &.danger {
    background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
  }
}

.stat-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

/* 图表区域 */
.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
  display: flex;
  align-items: center;
}

/* 数据表格 */
.data-table-card {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

/* 报告页脚 */
.report-footer {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 12px;
  
  p {
    margin: 5px 0;
  }
}

/* 打印样式 */
@media print {
  .summary-content {
    background: white;
  }
  
  .chart-card,
  .data-table-card {
    page-break-inside: avoid;
    box-shadow: none;
  }
  
  .report-header {
    page-break-after: avoid;
  }
}
</style>
